<template>
    <main-wrap>
        <template v-slot:header> 
            <Header title="商品分享"/>
        </template>
        <canvas id="canvas" style="display:none"></canvas>
        <img class="posterImg" :src="poster">

        <template v-slot:footer>
            <div class="bottomBox">
                <div class="item" @click="handeImg(1)"><i class="iconfont icon-baocun"></i>保存图片</div>
                <div class="item" @click="handeImg(2)"><i class="iconfont icon-JC_054"></i>分享</div>
            </div>
        </template>
    </main-wrap>
</template>

<script>
import { reactive,toRefs,getCurrentInstance,onMounted,computed } from 'vue'
import {useRoute,useRouter} from 'vue-router'
import { useStore } from 'vuex'
import {base64toFile,imgAgentUrl,H5CallAPPFuction} from '@/utils/common'
import {Toast} from 'vant'
import {loading} from '@/utils/common'
import mainWrap from '@/components/mainWrap.vue'
import Header from '@/components/header.vue'
import {
    addImgToCanvas,
    drawCircularImg,
    drawText,
    drawTextMoreLine,
    drawRectangle,
    compressImg
} from '@/utils/canvas' 

export default {
    components:{
       mainWrap,
       Header
    },
    props:{

    },
    setup(props,context){
        const router = useRouter()
        const route = useRoute()
        const store = useStore()
        const {proxy} = getCurrentInstance()

        const state = reactive({
            detail:computed(()=>store.state.arApi.detail),
            userInfo:computed(()=>store.state.arApi.userInfo),
            poster:'',
            isUpload:false  // 是否上传了base64图片
        })

        onMounted(async ()=>{
            if(!state.userInfo.userName){
                loading.close()
                router.push('/login')
                return
            }
            const goodsId = route.params.id
            const detailType = route.params.type
            if(detailType == 2){  // 拍卖详情
               await store.dispatch('arApi/get_auction_goods_detail',{goodsId})
            }else{ // 商品详情
               await store.dispatch('arApi/get_goods_detail',{goodsId})
            } 
            createCard()
        })

        // 绘制图片
        const createCard = async ()=>{
            loading.open()

            const avatar = imgAgentUrl(state.userInfo.headUrl)
            const imagesUrl = imgAgentUrl(state.detail.imageUrl)
            const phone = state.userInfo.userName
            const title = state.detail.title
            const introduce = state.detail.subtitle
            const artist = `艺术家：${state.detail.artist.nick}`
            const price = state.detail.internalPrice.decimalTwoString
            //----------------------
            const canvas_w = 648  // 画布的宽度
            const con_x = 46  // 主体部分放置元素的x坐标
            const top_h = 178 // 头部区域占据的高度
            const bottom_h = 500 // 底部区域占的高度（底部文字区域）
            const img_boder = 20  // 图片相框的厚度（边框）
            const f_width = 510  // 商品图片需要缩放的宽度
            // 压缩图片：f_height为压缩后的图片高度
            const {height:f_height} = await compressImg(imagesUrl,f_width,'auto') // 510的宽度等比压缩图片

            // 整个画布需要的高度:头部区域高度+中间商品图片高度+底部区域的高度（其中：中间商品图片高度=商品图片的高度+上下边框的高度）
            const canvas_h = top_h+(f_height+img_boder+img_boder)+bottom_h

            //console.log(`top_h:${top_h},f_height:${f_height},2*img_boder:${img_boder*2},bottom_h:${bottom_h}`)
            //console.log("canvas_h:",canvas_h)
            const canvas = document.getElementById("canvas")
            const ctx = canvas.getContext("2d")

            // 设置画布的高宽度
            canvas.width = canvas_w
            canvas.height = canvas_h
           
            await addImgToCanvas(ctx,"/h5/images/sbg.png",0,0,canvas_w,canvas_h)  // 绘制背景图片

            // 绘制圆形图像
            await drawCircularImg(ctx,avatar,96,96,46,50) // 头像

            //const tX = canvas.width / 2
            drawText(ctx,'fillText',`您的好友 ${phone}`,168,90,"34px Arial",'#F4C28B','left')
            drawText(ctx,'fillText','为您挑选了一个好礼物',170,135,"22px Arial",'#fff','left')

            // -----------------中间商品图片区域----------------------------------------------------------------------
           
            const goodsimg_x = con_x+20 // 商品图片x轴的位置
            // 获取压缩后的图片高度：f_height
            await addImgToCanvas(ctx,imagesUrl,goodsimg_x,198,f_width,'auto')  // 商品图片

            drawRectangle(ctx,'#f3d0a6',con_x,198,20,f_height) // 左边边框
            drawRectangle(ctx,'#f3d0a6',goodsimg_x+f_width,198,20,f_height) // 右边边框
            await addImgToCanvas(ctx,"/h5/images/sbd1.jpg",con_x,top_h,f_width+40,20) // 绘制上边框 
            await addImgToCanvas(ctx,"/h5/images/sbd2.jpg",con_x,top_h+f_height,f_width+40,20) // 绘制下边框
             
            //------底部区域-----------------------------------------------------------------------------------------------------
            // 标题
            const lingheight = 42  // 多行文字的行与行的艰巨
            const title_y = (top_h+f_height+img_boder*2)+40
            //drawTextMoreLine(ctx,title,18,2,con_x,title_y,'bold 30px Arial',"#F4C28B",lingheight)
            drawTextMoreLine(ctx,title,con_x,title_y,560,lingheight,'bold 30px Arial',"#F4C28B",2)
            
            // 作家
            const artist_y = title_y+lingheight*2 + 10 // lingheight*2：2行文字的高度
            drawText(ctx,'fillText',artist,con_x,artist_y,"24px Arial",'#fff','left')

            // 副标题
            const lingheight2 = 40  // 多行文字的行与行的艰巨
            const introduce_y = artist_y + 55 
            //drawTextMoreLine(ctx,introduce,23,2,con_x,introduce_y,'24px Arial',"#fff",lingheight2)
            drawTextMoreLine(ctx,introduce,con_x,introduce_y,560,lingheight,'24px Arial',"#fff",2)

            // 价格绘制
            const price_y = introduce_y+lingheight2*2+30 // lingheight2*2表示2行文字的高度
            drawText(ctx,'fillText','￥',con_x,price_y,"24px Arial",'#F4C28B','left')  // 价格符号
            drawText(ctx,'fillText',price,con_x+25,price_y,"36px Arial",'#F4C28B','left')  // 价格

            // 正品实物、全场包邮
            const flag_y = price_y + 40
            const icon_w = 120
            const icon_h = 44
            await addImgToCanvas(ctx,"/h5/images/zpsw.png",con_x,flag_y,icon_w,icon_h) // 正品实物
            await addImgToCanvas(ctx,"/h5/images/qcby.png",con_x+icon_w+20,flag_y,icon_w,icon_h) // 全场包邮

            // 绘制二维码
            const url = encodeURIComponent('https://www.tst.metayuanjie.com/h5/share/link?gid='+state.detail.goodsId)
            const ewm = '/h5/images/qrcode.png'//`http://api.ej12366.video/admin/get/qrcode?con=${url}` // '/h5/images/qrcode.png'
            await addImgToCanvas(ctx,ewm,con_x+350,introduce_y+70,200,200) // 二维码


            state.poster = canvas.toDataURL() 
            loading.close()

        }

        const handeImg = async (type)=>{
            // if(!state.isUpload){  // 没有上传
            //     await uploadBase64ToServe()
            // }
            const forAppData = {
                type,
                base64:state.poster
            }
            console.log("forAppData:",forAppData)
            H5CallAPPFuction('shareImage',JSON.stringify(forAppData))  // 调用app的loginSuccessful方法，并把用户信息传过去
        }

        
        const uploadBase64ToServe = async (base64Str)=>{
            // 把base64上传服务器
            return new Promise(async(resolve,reject) =>{
                const file = base64toFile(base64Str || state.poster)
                let fromData = new FormData()
                fromData.append('file', file)
                const res = await store.dispatch('arApi/upload_file',fromData)
                if(res.success){
                    state.isUpload = true
                    state.poster = res.url
                    resolve(res.url)
                }else{
                    console.log("base64上传服务器失败")
                    resolve(false)
                }
            })
        }

        return{
            ...toRefs(state),
            handeImg,
            imgAgentUrl
        }
    }
}
</script>

<style lang="scss" scoped>
    .posterImg{
        display: block;
        width: 648px;
        margin:0 auto;
        margin-top: 50px;
    }
    .bottomBox{
        display: flex;
        height: 100px;
        line-height: 100px;
        width: 100%;
        background: rgba(14, 97, 97, 0.8);
        .item{
            display: flex;
            flex: 1;
            justify-content: center; 
            align-items: center;
            font-size: 30px;
            color: var(--baseColor);
            text-align: center;
            i{
                margin: 0 5px 0 0;
            }
        }
    }
</style>